<template>
  <div>
    <avue-upload
      v-if="!this.$attrs.disabled||this.$attrs.listType=='picture-img'"
      style="display: inline-block;"
      v-bind="$attrs"
      v-on="$listeners"
      v-model="text"
      :propsHttp="propsHttp"
      :action="action">
    </avue-upload>
    <template v-if="this.$attrs.disabled">
      <el-button
        v-if="this.text!=null"
        type="primary"
        style="vertical-align: top;"
        :style="{'margin-left': (this.$attrs.listType=='picture-img'? '15px': 0)}"
        @click="handleDownload">下载</el-button>
      <span v-else-if="this.$attrs.listType!='picture-img'">无</span>
    </template>
  </div>
</template>

<script>
  import request from '@/router/axios'
  const DOWNLOAD_PREFIX = '/admin/sys-file/'
  export default {
    name: 'ZdUpload',
    data() {
      return {
        action: '/admin/sys-file/upload',
        text: undefined,
        propsHttp: {
          name: 'name',
          url: 'name',
          fileName: 'file',
          res: 'data'
        }
      }
    },
    computed: {},
    watch:{
      value: {
        handler (val) {
          this.initVal();
        },
        immediate: true
      },
      text: {
        handler (val) {
          if(!this.validatenull(val)){
            let result = this.text.substr(DOWNLOAD_PREFIX.length)
            this.$emit('input', result)
          }else{
            this.$emit('input', null)
          }
        }
      }
    },
    props: {
      value: {}
    },
    methods: {
      initVal(){
        if(!this.validatenull(this.value)){
          this.text = DOWNLOAD_PREFIX + this.value
        }else{
          this.text = null
        }
      },
      handleDownload() {
        return request({
          url: this.text,
          method: 'get',
          responseType: 'blob'
        }).then((response) => { // 处理返回的文件流
          const blob = response.data
          const link = document.createElement('a')
          link.href = URL.createObjectURL(blob)
          link.download = decodeURIComponent(response.headers['content-disposition'].split(';')[1].split('=')[1])
          document.body.appendChild(link)
          link.click()
          window.setTimeout(function() {
            URL.revokeObjectURL(blob)
            document.body.removeChild(link)
          }, 0)
        })
      }
    }
  }
</script>

<style lang="scss">
</style>
